package com.cqjtu.controller;

import com.cqjtu.enums.ResultCodeEnum;
import com.cqjtu.pojo.Result;
import com.cqjtu.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliOSSUtils aliOSSUtils;
    //本地上传
    /*@PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile image) throws IOException {

        //获取原始文件名
        String originalFilename = image.getOriginalFilename();

        //构造唯一文件名（不能重复）--uuid（通用唯一识别码)
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);
        String newFilename = UUID.randomUUID().toString() + extname;

        //将文件上传到服务器磁盘目录中
        image.transferTo(new File("E:\\image\\" + newFilename));

        return Result.success();
    }*/

    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile image) throws IOException {
        if(image == null){
            return Result.error(ResultCodeEnum.PARAM_LOST_ERROR);
        }

        //调用阿里云OSS工具类进行文件上传
        String url = aliOSSUtils.upload(image);

        System.out.println(url);
        return Result.success(url);
    }

}
